#!/usr/bin/env python
# coding=UTF-8
'''
@Author: 赵天天
@LastEditors: 赵天天
@email: dayday_1996@163.com
@Descripttion: 安全状态画像接口
@Date: 2019-04-28 17:32:26
@LastEditTime: 2019-05-20 14:58:27
'''

from flask import Blueprint, g
from psycopg2 import connect
from psycopg2.extras import RealDictCursor
import json
from config import config
from lib import auth
from lib.table import table
from lib.validform import V, ValidateForm

app = Blueprint(__name__ + "_app", __name__)


# 连接/关闭 数据库
@app.before_request
def setupdb():
    g.conn = connect(**config.DatabaseConfig.siem_stc)
    g.cursor = g.conn.cursor(cursor_factory=RealDictCursor)


@app.teardown_request
def unsetdb(exception):
    if g.cursor:
        g.cursor.close()
        g.cursor = None
    if g.conn:
        g.conn.close()
        g.conn = None


# 获得网站列表
@app.route('/api/safe/weblist', methods=['POST'])
@auth.permission("safetyProfile")
def weblist():
    try:
        tb = table()
        g.cursor.execute("""select
                                count(1) as total
                            from (
                                select 
                                info_sys_name
                                from  t_realtime_infosys_portrait 
                            where static_time = (select distinct max(static_time) 
                                    from  t_realtime_infosys_portrait 
                                    ) ) as b %s  """ % (tb.where(['b.info_sys_name'])))       
        total = g.cursor.fetchone()
  
        g.cursor.execute("""select * from ( select
                                distinct b.info_sys_id,
                                rank() over(order by  b.all_score desc) as rank,
                                b.info_sys_name,
                                coalesce((b.all_score-c.all_score),0) :: integer as  vara_score  ,
                                b.all_score :: integer,
                                b.real_score :: integer,
                                b.usability_score :: integer,
                                b.all_handle_score :: integer,
                                b.warning_score :: integer,
                                b.avg_all_score :: integer,
                                d2t(b.static_time) as static_time
                            from (
                                select
                                info_sys_name,
                                info_sys_id,
                                all_score,
                                realtime_risk_score as  real_score,
                                run_score as usability_score,
                                capability_score as all_handle_score,
                                risk_warn_score as warning_score,
                                avg_all_score,
                                static_time
                            from  t_realtime_infosys_portrait
                            where static_time = (select distinct static_time
                            from  t_realtime_infosys_portrait
                            order by static_time  desc  limit 1) ) as b
                            left  join  t_realtime_infosys_portrait as c
                            on b.info_sys_id = c.info_sys_id and c.static_time = (select distinct static_time
                                    from  t_realtime_infosys_portrait
                                    order by static_time  desc offset 1 limit 1) ) as b
                            %s %s %s %s """ % (tb.where(['b.info_sys_name']), tb.orderBy(), tb.offset(), tb.limit()))
        return json.dumps({
            "status": "success",
            "data": {
                "dataSource": g.cursor.fetchall(),
                "total": total
            }
        })
    except Exception as e:
        return json.dumps({"status": "except", 'msg': str(e)})


# 获得快速筛选信息
@app.route('/api/safe/fastfilter', methods=['POST'])
@auth.permission("safetyProfile")
def fastfilter():
    try:
        g.cursor.execute("""
        select d2t(COALESCE(max(static_time),CURRENT_DATE)) as static_time 
        from t_realtime_infosys_portrait
        """)
        newTime = g.cursor.fetchone()
        dataSource = {"newTime": newTime}
        return json.dumps({
            "status": "success",
            "data": dataSource
        })
    except Exception:
        return json.dumps({"status": "except", 'msg': '查询失败', 'warn': '异常'})


# 网站综合评分
@app.route('/api/safe/webcompreScore', methods=['POST'])
@auth.permission("safetyProfile")
def webcompreScore():
    try:
        g.cursor.execute("""
            select array_agg( COALESCE(total,0)) as total,
                   array_agg( COALESCE(total1)) as name
                from (       
                select *
                from (
                select count(distinct info_sys_id) as total,
                    '系统总数' as total1,
                    0 as index
                from t_realtime_infosys_portrait 
                where static_time = (select distinct max(static_time) 
                            from  t_realtime_infosys_portrait 
                            )
                UNION 
                select count(distinct info_sys_id) as twenty,
                    '0-20' ,
                    1 as index
                from t_realtime_infosys_portrait 
                where static_time = (select distinct max(static_time) 
                            from  t_realtime_infosys_portrait 
                            )
                and all_score>0 and all_score < 21 UNION 
                select count(distinct info_sys_id) as forty,
                    '21-40',
                    2 as index
                from t_realtime_infosys_portrait 
                where static_time = (select distinct max(static_time) 
                            from  t_realtime_infosys_portrait 
                            )
                and all_score>20 and all_score < 41 UNION 
                select count(distinct info_sys_id) as sixth,
                    '41-60' ,
                    3 as index
                from t_realtime_infosys_portrait 
                where static_time = (select distinct max(static_time) 
                            from  t_realtime_infosys_portrait 
                            )
                and all_score>40 and all_score < 61 UNION 
                select count(distinct info_sys_id) as eighty,
                    '61-80' ,
                    4 as index
                from t_realtime_infosys_portrait 
                where static_time = (select distinct max(static_time) 
                            from  t_realtime_infosys_portrait 
                            )
                and all_score>60 and all_score < 81 UNION 
                select count(distinct info_sys_id) as hundred,
                    '81-100' ,
                    5 as index
                from t_realtime_infosys_portrait 
                where static_time = (select distinct max(static_time) 
                            from  t_realtime_infosys_portrait  
                            )
                and all_score>80 and all_score < 101 ) as a
                order by index ) as a
                """)
        webNum = g.cursor.fetchone()
        remainder = [0]
        num = webNum['total'][0]
        for i in range(len(webNum['total'])):
            if i != 0: 
                num = num - webNum['total'][i]
                remainder.append(num)
        webNum['remainder'] = remainder
        g.cursor.execute("""
         select  COALESCE(avg(all_score),0) :: integer as  all_score,
                COALESCE(avg(realtime_risk_score),0) :: integer as  real_score,
                COALESCE(avg(run_score),0) :: integer as  usability_score,
                COALESCE(avg(capability_score),0) :: integer as  all_handle_score,
                COALESCE(avg(risk_warn_score),0) :: integer as  warning_score,
                COALESCE(avg(avg_all_score),0) :: integer as  avg_all_score
            from t_realtime_infosys_portrait 
            where static_time = (select distinct max(static_time) 
                    from  t_realtime_infosys_portrait 
                    )
        """)
        webScore = g.cursor.fetchone()
        g.cursor.execute("""
            select d2t(COALESCE(max(static_time),CURRENT_DATE)) as static_time 
            from t_realtime_infosys_portrait
        """)
        newTime = g.cursor.fetchone()
        return json.dumps({
            "status": "success",
            "data": {
                'webNum': webNum,
                'webScore': webScore,
                'newTime': newTime
            }
        })
    except Exception as e:
        return json.dumps({"status": "except", 'msg': '查询失败', 'warn': str(e)})


# 评分趋势 scoringTrend
@app.route('/api/safe/scoringTrend', methods=['POST'])
@auth.permission("safetyProfile")
def scoringTrend():
    try:
        form = ValidateForm(selectTime=['时间选择', V.required()])
        (flag, data) = form.validate()
        if not flag:
            data['status'] = 'fail'
            return json.dumps(data)
        select = eval(data['selectTime'])
        g.cursor.execute("""select COALESCE(max(static_time),CURRENT_DATE) as max 
                            from t_realtime_infosys_portrait
                           """)
        maxTime = g.cursor.fetchone()
        nowtime = maxTime['max']
        # 当查看为全部时 
        if select == 1000:
            g.cursor.execute("""SELECT  COALESCE(min(static_time),CURRENT_DATE)  as min
                                from t_realtime_infosys_portrait 
                                """)
            mintime = g.cursor.fetchone()['min']
            select = nowtime - mintime
            select = select.days  
            if select < 10:
                g.cursor.execute(""" WITH RECURSIVE t(static_time) AS (
                                        SELECT date_trunc('day', timestamp'%s')  
                                    UNION ALL
                                        SELECT static_time-interval '%s day' FROM t
                                    )
                                    select array_agg((to_date(xdata,'yyyy-mm-dd')) :: varchar) as xdata,
                                        array_agg(d.ydata) as ydata
                                    from (
                                        select d2t(b.static_time) as xdata,
                                            coalesce(c.all_score,0) as ydata
                                        from (SELECT static_time FROM t LIMIT 10) as b
                                        left join (select static_time,
                                                        avg(all_score) ::integer as all_score
                                                        from t_realtime_infosys_portrait 
                                            group by static_time) as c 
                                        on b.static_time = c.static_time
                                        order by b.static_time ) as d """ % (nowtime, 1))
            else:
                g.cursor.execute("""WITH RECURSIVE t(static_time) AS (
                                        SELECT date_trunc('day', timestamp'%s')  
                                    UNION ALL
                                        SELECT static_time-interval '%s day' FROM t
                                    )
                                    select array_agg((to_date(xdata,'yyyy-mm-dd')) :: varchar) as xdata,
                                        array_agg(d.ydata) as ydata
                                    from (
                                        select d2t(b.static_time) as xdata,
                                            coalesce(c.all_score,0) as ydata
                                        from (SELECT static_time FROM t LIMIT 10) as b
                                        left join (select static_time,
                                                        avg(all_score) ::integer as all_score
                                                        from t_realtime_infosys_portrait 
                                            group by static_time) as c 
                                        on b.static_time = c.static_time
                                        order by b.static_time ) as d """ % (nowtime, select / 10))
        else:
            g.cursor.execute(""" WITH RECURSIVE t(static_time) AS (
                                        SELECT date_trunc('day', timestamp'%s')  
                                    UNION ALL
                                        SELECT static_time-interval '%s day' FROM t
                                    )
                                    select array_agg((to_date(xdata,'yyyy-mm-dd')) :: varchar) as xdata,
                                        array_agg(d.ydata) as ydata
                                    from (
                                        select d2t(b.static_time) as xdata,
                                            coalesce(c.all_score,0) as ydata
                                        from (SELECT static_time FROM t LIMIT 10) as b
                                        left join (select static_time,
                                                        avg(all_score) ::integer as all_score
                                                        from t_realtime_infosys_portrait 
                                            group by static_time) as c 
                                        on b.static_time = c.static_time
                                        order by b.static_time ) as d """ % (nowtime, select / 10))
        dataSource = g.cursor.fetchone() 
        return json.dumps({
            "status": "success",
            "data": {'xdata': dataSource['xdata'], 'ydata': dataSource['ydata']}
        })
    except Exception as e:
        return json.dumps({"status": "except", 'msg': '查询失败', 'warn': str(e)})


# 威胁类型分布
@app.route('/api/safe/threatarea', methods=['POST'])
@auth.permission("safetyProfile")
def threatarea():
    try:
        g.cursor.execute("""
           select array_agg(coalesce(total, 0)) as total,
                array_agg(name) as risk_type
            from (
                select sum(scan_times) as  total,
                    info_sys_name as name
                from (
                select info_sys_id,
                    info_sys_name 
                from h_information_system_fdw 
                where state ='1') as a
                left join t_realtime_infosys_eventgrade as b
                on a.info_sys_id = b.info_sys_id
                group by info_sys_name
            ) as a
                """)
        dataSource = g.cursor.fetchone()
        return json.dumps({
            "status": "success",
            "data": dataSource
        })
    except Exception:
        return json.dumps({"status": "except", 'msg': '查询失败', 'warn': '异常'})


# 告警分布
@app.route('/api/safe/alarmarea', methods=['POST'])
@auth.permission("safetyProfile")
def alarmarea():
    try:
        g.cursor.execute("""select  coalesce(sum(scan_times),0) as value,
                                case t.event_grade when 1 then '低危'
                                                   when 2 then '中危' 
                                                   when 3 then '高危' 
                                                   when 4 then '严重' end as name
                            from (values(1), (2), (3) , (4)) as t(event_grade)
                            left join t_realtime_infosys_eventgrade as b
                            on t.event_grade = b.event_grade
                            group by t.event_grade
                            order by t.event_grade
                                """)
        dataSource = g.cursor.fetchall()
        return json.dumps({
            "status": "success",
            "data": dataSource
        })
    except Exception:
        return json.dumps({"status": "except", 'msg': '查询失败', 'warn': '异常'})


# 网站评分排名
@app.route('/api/safe/webScore', methods=['POST'])
@auth.permission("safetyProfile")
def webScore():
    try:
        tb = table()
        g.cursor.execute(""" select * from (
                                    select rank() over(order by  a.all_score desc) as rank,
                                            a.all_score  ,
                                            a.info_sys_name,
                                            a.info_sys_id,
                                            COALESCE((a.all_score -b.all_score),0) as vara_score
                                        from
                                        (select %s ::integer as all_score,
                                            info_sys_name,
                                            info_sys_id
                                        from t_realtime_infosys_portrait
                                        where static_time = (select distinct max(static_time) 
                                                    from  t_realtime_infosys_portrait 
                                                    )) as a 
                                        left join 
                                        (select %s ::integer as all_score,
                                            info_sys_name,
                                            info_sys_id
                                        from t_realtime_infosys_portrait
                                        where static_time = (select distinct static_time 
                                            from  t_realtime_infosys_portrait 
                                            order by static_time  desc offset 1 limit 1)) as b
                                        on a.info_sys_id = b.info_sys_id 
                                    ) as a
                               %s offset 0 limit 5
                        """ % (tb.dict['scoreType'], tb.dict['scoreType'], tb.orderBy()))
        dataSource = g.cursor.fetchall()
        return json.dumps({
            "status": "success",
            "data": dataSource
        })
    except Exception:
        return json.dumps({"status": "except", 'msg': '查询失败', 'warn': '异常'})


# 运行情况， 分险预警， 历史安全情况
@app.route('/api/safe/safescore', methods=['POST'])
@auth.permission("safetyProfile")
def safescore():
    try:
        form = ValidateForm(website_id=['网站编号', V.required()])
        (flag, data) = form.validate()
        if not flag:
            data['status'] = 'fail'
            return json.dumps(data)
        # 实时风险
        g.cursor.execute("""select coalesce(max(attck_event_num),0) as attck_event_num,
                                coalesce(max(import_attackevent_num),0) as import_attackevent_num,
                                coalesce(max(step1_assert_num),0) as step1_assert_num,
                                coalesce(max(step2_assert_num),0) as step2_assert_num,
                                coalesce(max(step3_assert_num),0) as step3_assert_num,
                                coalesce(max(step4_assert_num),0) as step4_assert_num,
                                coalesce(max(step5_assert_num),0) as step5_assert_num,
                                coalesce(max(all_assert_num),0) as all_assert_num
                            from t_realtime_infosys_risk
                            where info_sys_id = '%s'
                            and static_date=  (select distinct max(static_date) 
                                from  t_realtime_infosys_risk )
                               """ % data['website_id'])
        realrisk = g.cursor.fetchone()

        g.cursor.execute("""  select coalesce(max(static_date), now())  as maxtime
                              from t_realtime_infosys_run
                               """)
        maxtime = g.cursor.fetchone()

        # 运行情况 折线图
        g.cursor.execute("""WITH RECURSIVE t(static_time) AS (
                                SELECT date_trunc('day', timestamp'%s')  
                            UNION ALL
                                SELECT static_time - interval '1 day' FROM t
                            )
                        select array_agg(to_char(a.static_time,'yyyy-mm-dd')) as static_time,
                            array_agg(coalesce(living_node_num,0)) as living_node_num,
                            coalesce(max(living_node_num),0) as max_node_num,
                            coalesce(min(living_node_num),0) as min_node_num
                        from (select * from  
                                    (select t.static_time  from t  limit 10 ) as T  
                            order by static_time ) as a
                        left join t_realtime_infosys_run as b
                        on a.static_time = b.static_date and info_sys_id = '%s' """ % (maxtime['maxtime'],
                                                                                       data['website_id']))
        usability = g.cursor.fetchone()

        # 运行情况 当前活跃节点
        g.cursor.execute("""select coalesce(max(living_node_num),0) as living_node_num
                            from t_realtime_infosys_run
                            where static_date=  (select distinct max(static_date) 
                                        from  t_realtime_infosys_risk )
                                and info_sys_id = '%s' """ % data['website_id'])
        nowliving_node = g.cursor.fetchone()

        # coalesce(num， 0) 得在聚合后好使
        g.cursor.execute("""select array['0', coalesce(max(operate24_risk_num),0) || '' ,  '', '' , '' ] as operate24,
                                array['', coalesce(max(operate24_risk_num),0) || '' , coalesce(max(operate48_risk_num),0)  || '', '' , '' ] as operate48,
                                array['' , '', coalesce(max(operate48_risk_num),0)  || '', coalesce(max(operate72_risk_num),0) || '' , '' ] as operate72,
                                array['' ,'' , '' , coalesce(max(operate72_risk_num),0) || '' , coalesce(max(operate72up_risk_num),0) || '' ] as operate73,
                                coalesce(max(operate24_risk_num),0)+coalesce(max(operate48_risk_num),0)+coalesce(max(operate72_risk_num),0)+coalesce(max(operate72up_risk_num),0)
                                + coalesce(max(not_operate_risk_num),0) as total_risk,
                                coalesce(max(operate24_risk_num)+max(operate48_risk_num)+max(operate72_risk_num)+max(operate72up_risk_num),0  	) as read_risk,
                                coalesce(max(not_operate_risk_num),0) as not_operate_risk_num
                            from t_realtime_infosys_operate
                            where static_date = (select distinct static_date 
                                                    from  t_realtime_infosys_operate 
                                                    order by static_date  desc offset 1 limit 1)
                                and info_sys_id = '%s'
                                """ % data['website_id'])
        operate = g.cursor.fetchone()
        # 风险预警
        g.cursor.execute("""select risk_item,
                                effect_assert_num 
                            from t_realtime_infosys_warn
                            where static_date=  (select distinct max(static_date) 
                                        from  t_realtime_infosys_risk )
                                and info_sys_id = '%s'""" % data['website_id'])
        riskwarning = g.cursor.fetchall()
        # 历史安全
        g.cursor.execute("""select avg_real_score,
                                avg_all_handle_score,
                                avg_warning_score,
                                avg_run_score,
                                avg_all_score
                            from t_realtime_infosys_portrait
                            where static_time=  (select distinct max(static_time) 
                                        from  t_realtime_infosys_portrait )
                                and info_sys_id = '%s'
                                """ % data['website_id'])
        historySecurity = g.cursor.fetchone()
        return json.dumps({
            "status": "success",
            "data": {
                'riskdata': realrisk,
                "usability": {
                    'usability': usability,
                    'nowliving_node': nowliving_node['living_node_num'],
                },
                'operate': operate,
                'riskwarning': riskwarning,
                'historySecurity': historySecurity,
                'realrisk': realrisk
            }
        })
    except Exception as e:
        return json.dumps({"status": "except", 'msg': '获取失败', 'warn': str(e)})


# 评分与排名 scoreranking
# 运行情况， 分险预警， 历史安全情况
@app.route('/api/safe/scoreranking', methods=['POST'])
@auth.permission("safetyProfile")
def scoreranking():
    try:
        form = ValidateForm(website_id=['网站编号', V.required()])
        (flag, data) = form.validate()
        if not flag:
            data['status'] = 'fail'
            return json.dumps(data)
        # 实时风险
        g.cursor.execute("""select *
                            from (
                            select info_sys_id ,
                                all_score ::integer
                                as all_score ,
                                rank() over (order by all_score desc) ::integer as  all_scorerink,
                                realtime_risk_score ::integer as real_score,
                                rank() over (order by realtime_risk_score desc)  ::integer as   real_scorerink,
                                capability_score ::integer as all_handle_score ,
                                rank() over (order by capability_score desc) ::integer as  all_handle_scorerink,
                                run_score ::integer as usability_score,
                                rank() over (order by run_score desc) ::integer as usability_scorerink ,
                                risk_warn_score ::integer as warning_score,
                                rank() over (order by risk_warn_score  desc) ::integer as  warning_scorerink,
                                avg_all_score ::integer as avg_all_score,
                                rank() over (order by avg_all_score  desc) ::integer as  avg_all_scorerink
                            from t_realtime_infosys_portrait
                            where static_time=  (select distinct max(static_time) 
                                from  t_realtime_infosys_portrait )) as a 
                            where info_sys_id = '%s' """ % data['website_id'])
        scoringrank = g.cursor.fetchone()
        g.cursor.execute("""select  count(info_sys_id) as webcount 
                            from t_realtime_infosys_portrait where 
                            static_time=  (select distinct max(static_time) 
                                            from  t_realtime_infosys_portrait ) """)
        websiteNUm = g.cursor.fetchone()
        
        g.cursor.execute("""  select coalesce(capability_score,0) ::integer as all_handle_score ,
                                    coalesce(run_score,0) ::integer as usability_score ,
                                    coalesce(risk_warn_score,0)  ::integer as warning_score ,
                                    coalesce(avg_all_score,0) ::integer as avg_all_score ,
                                    coalesce(realtime_risk_score,0) ::integer as real_score
                                from t_realtime_infosys_portrait 
                                where info_sys_id = '%s'
                                    and static_time=  (select distinct max(static_time) 
                                                        from  t_realtime_infosys_portrait )
                                                                         """ % data['website_id'])
        radar = g.cursor.fetchone()
        radarList = []
        if radar is None: 
            radarList = [0, 0, 0, 0, 0]
        else:
            for key, values in radar.items():
                radarList.append(values)
        return json.dumps({
            "status": "success",
            "data": {
                'scoringrank': scoringrank,
                'radar': radarList,
                'websitenum': websiteNUm['webcount']
            }
        })
    except Exception as e:
        return json.dumps({"status": "except", 'msg': '获取失败', 'warn': str(e)})


# 安全状态 与 平均安全评分状态
@app.route('/api/safe/avgscore', methods=['POST'])
@auth.permission("safetyProfile")
def avgscore():
    try:
        form = ValidateForm(website_id=['网站编号', V.required()])
        (flag, data) = form.validate()
        if not flag:
            data['status'] = 'fail'
            return json.dumps(data)
        g.cursor.execute("""select COALESCE(max(static_time),CURRENT_DATE) as max 
                            from t_realtime_infosys_portrait """)
        maxTime = g.cursor.fetchone()
        nowtime = maxTime['max']
        g.cursor.execute("""WITH RECURSIVE t(static_time) AS (
                                SELECT date_trunc('day', timestamp'%s')  
                            UNION ALL
                                SELECT static_time-interval '1 day' FROM t
                            )
                            select array_agg((to_char(static_time,'yyyy-mm-dd')) ::varchar ) as static_time,
                                array_agg(all_score) as all_score,
                                array_agg(avg_all_score) as avg_all_score
                            from (
                                select a.static_time as static_time,
                                    coalesce(b.all_score,0) as all_score,
                                    coalesce(b.avg_all_score,0) as avg_all_score
                                from (
                                    select static_time 
                                    from t limit 10 ) as a 
                                left join (select 
                                    all_score,
                                    avg_all_score,
                                    static_time
                                    from  t_realtime_infosys_portrait where  info_sys_id = '%s'
                                    group by static_time,
                                    all_score,
                                    avg_all_score) as b
                                on a.static_time  = b.static_time
                                order by a.static_time
                            ) as c """ % (nowtime, data['website_id']))
        dataSource = g.cursor.fetchone()
        return json.dumps({
            "status": "success",
            "data": {
                'All_score': dataSource['all_score'],
                'Avg_all_score': dataSource['avg_all_score'],
                'Static_time': dataSource['static_time']
            }
        })
    except Exception as e:
        return json.dumps({"status": "except", 'msg': '获取失败', 'warn': str(e)})


# 获取最新时间
@app.route('/api/safe/newtimewebsite', methods=['POST'])
@auth.permission("safetyProfile")
def newtimewebsite():
    try:
        form = ValidateForm(website_id=['网站编号', V.required()])
        (flag, data) = form.validate()
        if not flag:
            data['status'] = 'fail'
            return json.dumps(data)
        # 实时风险
        g.cursor.execute("""select info_sys_name,
                                d2t(static_time) as static_time
                            from t_realtime_infosys_portrait 
                            where info_sys_id = '%s'
                            and static_time = (
                            select max(static_time) from t_realtime_infosys_portrait )""" % data['website_id'])
        timeweb = g.cursor.fetchone()
        return json.dumps({
            "status": "success",
            "data": timeweb
        })
    except Exception as e:
        return json.dumps({"status": "except", 'msg': str(e), 'warn': str(e)})


# 网站基本信息
@app.route('/api/safe/getwebmsg', methods=['POST'])
@auth.permission("safetyProfile")
def getwebmsg():
    try:
        form = ValidateForm(website_id=['系统编号', V.required()])
        (flag, data) = form.validate()
        if not flag:
            data['status'] = 'fail'
            return json.dumps(data)
        # 实时风险
        g.cursor.execute("""select info_sys_name,
                                deploy_date,
                                node_name,
                                coalesce(node_num,0) as node_num,
                                sys_desc
                            from t_realtime_infosys_portrait
                            where static_time=  (select distinct max(static_time) 
                                        from  t_realtime_infosys_portrait )
                                and info_sys_id = '%s'""" % data['website_id'])
        webmsg = g.cursor.fetchone()
        return json.dumps({
            "status": "success",
            "data": webmsg
        })
    except Exception:
        return json.dumps({"status": "except", 'msg': '获取失败', 'warn': '异常'})
